import axios from 'axios'
import {MessageBox, Message} from 'element-ui'
import store from '@/store'
import {getToken} from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

service.interceptors.request.use(
  config => {
    // if (store.getters.token) {
    //   config.headers['X-Token'] = getToken()
    // }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */
  response => {
    const res = response.data
    if (res.code !== 200) {
      Message({
        message: res.message || '出错啦，请联系管理员！',
        type: 'error',
        center: true,
        duration: 3 * 1000
      })
      return Promise.reject(new Error(res.message || ''))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message || '服务器出错啦，请联系管理员！',
      type: 'error',
      center: true,
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
